package  com.hx.base.servlet.velocity;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.VelocityResult;
import org.apache.struts2.views.velocity.VelocityManager;
import org.apache.velocity.Template;
import org.apache.velocity.context.Context;

import com.hx.util.resource.ResourceUtil;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;

public class VelocityHtmlResult extends VelocityResult{

    private static final long serialVersionUID = 1L;
    private static final Logger LOG = LoggerFactory.getLogger(VelocityHtmlResult.class);
    private static final String IS_BACKPAGE = "is_backpage";
    private static final String TRUE = "true";
    private static final String RUN_MODE = "run.mode";
    private static final String DEV = "dev";
    private static final String WEB_ROOT = "dev.WebRoot.dir";
    public VelocityHtmlResult() {
        super();
    }
    public VelocityHtmlResult(String location) {
        super(location);
    }
  
    private VelocityManager velocityManager;
    
    private String redirectUrl;
    public String getRedirectUrl() {
		return redirectUrl;
	}
	public void setRedirectUrl(String redirectUrl) {
		this.redirectUrl = redirectUrl;
	}
	@Inject
    public void setVelocityManager(VelocityManager mgr) {
        this.velocityManager = mgr;
    }
	
	@Override
    public void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {
        ValueStack stack = ActionContext.getContext().getValueStack();
        
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();
        ServletContext servletContext = ServletActionContext.getServletContext();
        velocityManager.init(servletContext);
        String path = "" ; 
        try {
            String encoding = getEncoding(finalLocation);
            String contentType = getContentType(finalLocation);

            if (encoding != null) {
                contentType = contentType + ";charset=" + encoding;
            }

            Template t = getTemplate(stack, velocityManager.getVelocityEngine(), invocation, finalLocation, encoding);
            //进入action之后,从stack中获取值,存在则插入request中
            String backValue = (String)stack.findValue(IS_BACKPAGE);
            if( backValue != null){
                request.setAttribute(IS_BACKPAGE, backValue);
            }
            Context context = createContext(velocityManager, stack, request, response, finalLocation);
          
            //通过模板名获取配置key值
            String key = finalLocation.substring(finalLocation.lastIndexOf("/")+1,finalLocation.length()).replace(".vm", "");
            if(DEV.equals(ResourceUtil.getStrValue(RUN_MODE))){
            	 path  =ResourceUtil.getStrValue(WEB_ROOT) + ResourceUtil.getStrValue(key);
            }else{
                 path  = servletContext.getRealPath("/") + ResourceUtil.getStrValue(key);
            }
            LOG.debug("index html path is [" + path + "]" );
         
            File file = new File(path);
            if(file.exists()){
               file.delete();
            }
            file.createNewFile();
            FileOutputStream outStream = new FileOutputStream(file);
            OutputStreamWriter htmlwriter = new OutputStreamWriter(outStream,encoding);       
            BufferedWriter sw = new BufferedWriter(htmlwriter);     
            t.merge(context, sw); 
            sw.flush();     
            sw.close();     
            outStream.close();
           
            //页面跳转
            if (redirectUrl == null || "".equals(redirectUrl)){
            	redirectUrl = request.getContextPath() + ResourceUtil.getStrValue(key);
            }
            LOG.debug(this.getClass() + " Velocity to Html [finalLocation = " +finalLocation +"][output = " + path +"][redirectUrl = " + redirectUrl + "]");
            servletContext.setAttribute(key, TRUE);
            response.sendRedirect(redirectUrl);
          
        } catch (Exception e) {
            LOG.error("Unable to render Velocity Template, '" + finalLocation + "'" +"; outStream file is '" + path + "'", e);
            throw e;
        }

        return;
    }



}